import {
  collectArticleApi,
  followUserApi,
  getArticleApi,
  getArticleDetailApi,
  likeArticleApi,
  uncollectArticleApi,
  unfollowUserApi,
  unlikeArticleApi,
} from '@/api/article';
import { AppDispatch } from '..';
import { Toast } from 'antd-mobile';
//获取首页列表数据
export const getArticleAction = (channel_id: number, timestamp = Date.now()) => {
  return async (dispatch: AppDispatch) => {
    const res = await getArticleApi(channel_id, timestamp);
    dispatch({ type: 'article/setArticleData', payload: { channel_id, data: res.data } });
  };
};
//下拉刷新数据
export const refreshArticleAction = (channel_id: number) => {
  return async (dispatch: AppDispatch) => {
    const res = await getArticleApi(channel_id);
    dispatch({ type: 'article/refresh', payload: { channel_id, data: res.data } });
  };
};

//获取文章详情
export const getArticleDetailAction = (article_id: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await getArticleDetailApi(article_id);
    dispatch({ type: 'article/setArticleDetail', payload: res.data });
  };
};
//清除文章详情
export const clearArticleDetailAction = () => {
  return async (dispatch: AppDispatch) => {
    dispatch({ type: 'article/setArticleDetail', payload: {} });
  };
};

//给文章点赞 //取消文章点赞
export const likeArticleAction = (article_id: string, hasLiked: Boolean) => {
  return async () => {
    //如果已经点赞了，就取消点赞，否则就点赞
    if (hasLiked) {
      await unlikeArticleApi(article_id);
    } else {
      await likeArticleApi(article_id);
    }
  };
};
//收藏文章 //取消收藏文章
export const collectArticleAction = (article_id: string, hasCollected: Boolean) => {
  return async () => {
    //如果已经收藏了，就取消收藏，否则就收藏
    if (hasCollected) {
      await uncollectArticleApi(article_id);
    } else {
      await collectArticleApi(article_id);
    }
  };
};

//关注用户
export const followUserAction = (target: string, hasFollowed: boolean) => {
  return async () => {
    if (hasFollowed) {
      //取消关注用户
      await unfollowUserApi(target);
    } else {
      await followUserApi(target);
    }
    Toast.show({ content: hasFollowed ? '取消关注成功' : '关注成功' });
  };
};
